<template>
  <div ref="svga" :id="svId" class="app-svga"></div>
</template>

<script>
import SVGA from "svgaplayerweb";
let svgaId = Math.round(Math.random() * (19999 - 1) + 1); // id序号
export default {
  props: {
    src: {
      type: String,
      required: true
    },
    loops: {
      type: Number,
      default: 1
    },
    mode: {
      type: String,
      default: "AspectFit"
    },
    onlyTag: {
      type: String
    },
    onFrame: {
      type: Function,
      default: () => {}
    },
    onFinished: {
      type: Function,
      default: () => {}
    },
    destroy: {
      type: Function,
      default: () => {}
    }
  },

  data() {
    return {
      svId: `svga-id-${svgaId++}` // 动态生成id,处理页面多个svga的情况
    };
  },

  mounted() {
    // 创建player
    let player = new SVGA.Player(`#${this.svId}`);
    player.loops = this.loops || Number.MAX_SAFE_INTEGER;
    player.clearsAfterStop = false;
    // 创建解析者
    let parser = new SVGA.Parser(`#${this.svId}`);
    parser.load(this.src, videoItem => {
      player.setVideoItem(videoItem);
      player.setContentMode(this.mode);
      player.startAnimation();
      player.onFinished(() => {
        player.clear();
        this.onFinished?.(this.onlyTag);
        this.destroy();
      });
      player.onFrame(frame => this.onFrame?.(frame, this.onlyTag));
    });
  },
  beforeUnmount() {
    console.log("beforeDestroy" + this.svId);
  }
};
</script>

<style lang="scss">
.app-svga {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  pointer-events: none;
}
</style>
